package avishay.balderman.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;

public abstract class TeamMemberHelper 
{
	public static void addTeamMember(HttpServletRequest req)
	{
		TeamMember teamMember = new TeamMember();
		teamMember.setFirstName(req.getParameter("firstName"));
		teamMember.setLastName(req.getParameter("lastName"));
		teamMember.setEmail(req.getParameter("email"));
		teamMember.setAddress(req.getParameter("address"));
		List<String> phoneNumbers = getPhoneNumbers(req.getParameter("phoneNumbers"));
		teamMember.setPhoneNumbers(phoneNumbers); 
		// what about the birthday? -talk to Aryeh
		addTeamMember(teamMember);
	}
	private static List<String> getPhoneNumbers(String phoneNumbers)
	{
		List<String> result = new ArrayList<String>();
		if(phoneNumbers == null || phoneNumbers.length() < 1)
		{
			return result;
		}
		StringTokenizer stringTokenizer = new StringTokenizer(phoneNumbers, ",");
		while(stringTokenizer.hasMoreTokens())
		{
			result.add(stringTokenizer.nextToken());
		}
		return result;
	}
	public static void addTeamMember(TeamMember teamMember)
	{
		logger.info("About to persist the teamMember " + teamMember);
		EntityManagerFactory entityManagerFactory = EMF.get();
		try
		{
			EntityManager entityManager = entityManagerFactory.createEntityManager();
			EntityTransaction transaction = entityManager.getTransaction();
			transaction.begin();
			entityManager.persist(teamMember);
			transaction.commit();
		}
		finally
		{
			entityManagerFactory.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	public static Collection<TeamMember> getTeamMembers()
	{
		EntityManagerFactory entityManagerFactory = EMF.get();
		try
		{
			EntityManager entityManager = entityManagerFactory.createEntityManager();
			Query linksQuery = entityManager.createQuery("SELECT t FROM TeamMember t");
			List resultList = linksQuery.getResultList();
			return (Collection<TeamMember>)resultList;
		}
		finally
		{
			entityManagerFactory.close();
		}
	}
	@SuppressWarnings("unchecked")
	public static List<String> getEmailAddresses() 
	{
		EntityManagerFactory entityManagerFactory = EMF.get();
		try
		{
			EntityManager entityManager = entityManagerFactory.createEntityManager();
			Query linksQuery = entityManager.createQuery("SELECT t.email FROM TeamMember t");
			List resultList = linksQuery.getResultList();
			return (List<String>)resultList;
		}
		finally
		{
			entityManagerFactory.close();
		}
		
	}
	private static Logger logger = Logger.getLogger("avishay.balderman.dao.TeamMemberHelper");

}
